package antlr.sql;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

public class SQLAnalyzer {
    public static void main(String[] args) {
        // 输入的SQL查询
        String sql = "SELECT field1 AS f1, field2 FROM table1 AS t1 where a=1 and b= 1";

        // 创建一个输入流
        CharStream input = CharStreams.fromString(sql);

        // 创建一个词法分析器
        SqlLexer lexer = new SqlLexer(input);

        // 创建一个词法符号的流
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // 创建一个语法分析器
        SqlParser parser = new SqlParser(tokens);

        // 解析输入
        SqlParser.QueryContext query = parser.query();

        // 遍历解析树，提取字段和表名
        for (SqlParser.ColumnContext column : query.select_clause().column_list().column()) {
            System.out.println("Field: " + column.IDENTIFIER().getText());
            if (column.alias() != null) {
                System.out.println("Alias: " + column.alias().IDENTIFIER().getText());
            }
        }

        SqlParser.Table_referenceContext table = query.from_clause().table_reference();
        System.out.println("Table: " + table.IDENTIFIER().getText());
        if (table.alias() != null) {
            System.out.println("Alias: " + table.alias().IDENTIFIER().getText());
        }

        for (SqlParser.ConditionContext conditionContext : query.where_caluse().condition().condition()) {

            System.out.println("Condition: " + conditionContext.getText());
            for (SqlParser.ConditionContext context : conditionContext.condition()) {

            }
        }
    }
}
